﻿using System.Web.Mvc;
using System.Web.Routing;
using LINQtoNHibernateMVC.Core.Domain;
using LINQtoNHibernateMVC.Infrastructure.DataAccess;
using LINQtoNHibernateMVC.Infrastructure.DataAccess.Impl;
using StructureMap;
using StructureMap.Attributes;
using NHibernate;

namespace LINQtoNHibernateMVC.Web {
	public class BootStrapper {
		internal static void RegisterIoC() {
			ObjectFactory.Initialize(x => {
				x.ForRequestedType<ISessionFactory>()
					.CacheBy(InstanceScope.Singleton)
					.TheDefault.Is.ConstructedBy(() => new NHibernateHelper().BuildSessionFactory());
	      
				x.ForRequestedType<ISession>()
					.CacheBy(InstanceScope.Hybrid)
					.TheDefault.Is.ConstructedBy(ctx =>
				{
					var session = ctx.GetInstance<ISessionFactory>().OpenSession();
					session.FlushMode = FlushMode.Commit;
					session.BeginTransaction();
					return session;
				});
				x.ForRequestedType<IRepository>().TheDefaultIsConcreteType<Repository>();
			});
		}
		
		public static void RegisterIoCControllerFactory(){
			ControllerBuilder.Current.SetControllerFactory(new StrucureMapControllerFactory());
		}

		public static void RegisterRoutes(RouteCollection routes){
			routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

			routes.MapRoute(
				"Default",                                              // Route name
				"{controller}/{action}/{id}",                           // URL with parameters
				new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
			);
		}
	}
}
